package com.ruoyi.ora.netty.server;

import com.ruoyi.ora.netty.channel.ChannelTcpInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 测控通道TCP协议服务端
 */
public class ChannelTcpServerThread extends Thread {

    private Logger logger = LoggerFactory.getLogger(ChannelTcpServerThread.class);

    EventLoopGroup bossGroup = null;
    EventLoopGroup workerGroup = null;

    private int port;

    public ChannelTcpServerThread(int port) {
        this.port = port;
    }

    @Override
    public void run() {
        try {
            int nThreads = 1;
            bossGroup = new NioEventLoopGroup(nThreads);
            workerGroup = new NioEventLoopGroup(nThreads);
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 65535)
                    .option(ChannelOption.SO_RCVBUF, 65535)
                    .childHandler(new ChannelTcpInitializer());

            // 绑定端口，同步等待成功
            ChannelFuture channelFuture = bootstrap.bind(port).sync();
            logger.info("服务端启动成功，端口号：" + port);
            // 等待服务监听端口关闭
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
                e.printStackTrace();
        } finally {
            try {
                workerGroup.shutdownGracefully();
                bossGroup.shutdownGracefully();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }


}
